﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;

namespace UI.Web.MVC.Constructor.Common
{
    public class DatabaseHelper
    {
        /// <summary>
        /// Створюємо базу даних
        /// </summary>
        /// <param name="databseName">Назва бази даних</param>
        /// <returns>Створено || Не стоворено</returns>
        public static bool CreateDataBase(string databseName)
        {
            var info = new DirectoryInfo(string.Format(@"C:\DataBases\{0}", databseName + "_PROTOTYPE"));
            info.Create();
            var sqlConnection = new SqlConnection("server=10.7.1.10;database=SYSTEM_PROTOTYPE;user=sa;password=123456;database=master");
            string str = string.Format("create database [{0}] ",
                              databseName.ToUpper() + "_PROTOTYPE");

            //var tt = new StreamReader(HttpContext.Current.Server.MapPath("~/DBScripts/Scripts.sql"));
            //string str2 = tt.ReadToEnd();

            string str2 = string.Format("use [{0}]", databseName.ToUpper() + "_PROTOTYPE");
            string str3 = "create  table PRODUCT ( ID int not null primary key identity, NAME varchar(50), CONNECTION_STRING varchar(100))";

            var myCommand = new SqlCommand(str, sqlConnection);
            var myCommand2 = new SqlCommand(str2, sqlConnection);
            var myCommand3 = new SqlCommand(str3, sqlConnection);
            try
            {
                sqlConnection.Open();
                myCommand.ExecuteNonQuery();
                myCommand2.ExecuteNonQuery();
                myCommand3.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
                return false;
            }
            finally
            {
                if (sqlConnection.State == ConnectionState.Open)
                {
                    sqlConnection.Close();
                }
            }
            return true;
        }
    }
}